package com.niiwoo.civet.user.service.local.dataflow;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.user.dao.entity.DataStatus;
import com.niiwoo.civet.user.dao.entity.IdentityInfo;
import com.niiwoo.civet.user.dao.entity.UcAccount;
import com.niiwoo.civet.user.dao.entity.UserBasicInfo;
import com.niiwoo.civet.user.dao.mapper.DataStatusMapperExt;
import com.niiwoo.civet.user.dao.mapper.IdentityInfoMapperExt;
import com.niiwoo.civet.user.dao.mapper.UserAccountMapperExt;
import com.niiwoo.civet.user.dao.mapper.UserBasicInfoMapperExt;
import com.niiwoo.civet.user.dto.request.df.BankInfoRequestDTO;
import com.niiwoo.civet.user.dto.request.df.StartAfterLoginRequestDTO;
import com.niiwoo.civet.user.dto.response.IdentityInfoBackflowDTO;
import com.niiwoo.civet.user.enums.UserDataStatusEnum;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.tiancheng.component.TianchengDataFlowService;
import com.niiwoo.tripod.tiancheng.enums.FunctionCodeEnum;
import com.niiwoo.tripod.tiancheng.request.common.TianchengUapRequest;
import com.niiwoo.tripod.tiancheng.request.df.*;
import com.niiwoo.tripod.tiancheng.response.common.TianchengUapResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

/**
 * 天秤数据回流服务
 * Created by lujing on 2017/12/2.
 */
@Slf4j
@Service
public class UserDataBackFlowService {

    private SimpleDateFormat format01 = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private TianchengDataFlowService tianchengDataFlowService;
    @Autowired
    private PrivacyMasks privacyMasks;
    @Autowired
    private UserBasicInfoMapperExt userBasicInfoMapperExt;
    @Autowired
    private UserAccountMapperExt userAccountMapperExt;
    @Autowired
    private DataStatusMapperExt dataStatusMapperExt;
    @Autowired
    private IdentityInfoMapperExt identityInfoMapperExt;




    /**
     * 登录后启动数据回流前置处理
     * @param startAfterLoginRequestDTO
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public StartAfterLoginRequest startAfterLoginBackFlow(StartAfterLoginRequestDTO startAfterLoginRequestDTO){
        StartAfterLoginRequest request = new StartAfterLoginRequest();
        BeanUtils.copyProperties(startAfterLoginRequestDTO, request);

        UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(startAfterLoginRequestDTO.getUserId());
        if (userBasicInfo!=null){
            request.setUserName(userBasicInfo.getNickName());
        }
        Long currTime = System.currentTimeMillis() * 1000;
        request.setStartTime(currTime);
        request.setCreateTime(currTime);
        return request;
    }


    /**
     * 个人信息-身份认证信息回流
     * @param userId
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public IdentityInfoRequest identityAuthBackFlow(String userId){
        log.info("identityAuthBackFlow.userId={}", userId);
        IdentityInfoRequest request = new IdentityInfoRequest();
        request.setUserId(userId.toString());

        //查询用户账户
        UcAccount ucAccount = userAccountMapperExt.selectByPrimaryKey(userId);
        log.info("identityAuthBackFlow.userId={},ucAccount={}", userId, JSON.toJSONString(ucAccount));
        if (ucAccount!=null){
            request.setMobilePhone(decryptPrivacy(ucAccount.getMobileNo()));
        }

        //查询用户身份信息
        IdentityInfo identityInfo = identityInfoMapperExt.selectByPrimaryKey(userId);
        log.info("identityAuthBackFlow.userId={},identityInfo={}", userId, JSON.toJSONString(identityInfo));
        if (identityInfo!=null){
            request.setRealName(identityInfo.getName());
            request.setCardType(1);
            request.setCardValidity(formatDate(identityInfo.getEndDate()));
            request.setCardNO(decryptPrivacy(identityInfo.getIdCard()));
            request.setCardAddress(identityInfo.getAddress());
            request.setUpdateTime(identityInfo.getUpdateTime().getTime());
        }

        //查询用户实名认证状态
        DataStatus dataStatus = dataStatusMapperExt.selectByUserIdAndType(userId, UserDataTypeEnum.TWO_ELEMENT.getValue());
        log.info("identityAuthBackFlow.userId={},dataStatus={}", userId, JSON.toJSONString(dataStatus));
        if (dataStatus!=null && UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus()==dataStatus.getDataStatus()){
            request.setCertificationStatus(UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus().intValue());
        } else {
            request.setCertificationStatus(UserDataStatusEnum.RealNameAuthStatus.NOT_CERTIFIED.getStatus().intValue());
        }
        if (dataStatus!=null){
            request.setCertificationTime(dataStatus.getUpdateTime().getTime());
        }
        return request;
    }

    private String formatDate(Date date) {
        return date == null ? null : format01.format(date);
    }

    private String decryptPrivacy(String s) {
        return StringUtils.hasText(s) ? privacyMasks.decryptPrivacy(s) : null;
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public IdentityInfoRequest identityAuthQuery(String userId) {
        if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManagerHolder.clear();
            HintManager hintManager = HintManager.getInstance();
            hintManager.setMasterRouteOnly();
        }
        return identityAuthBackFlow(userId);
    }

    /**
     * 个人实名信息回流
     *
     * @param userId
     */
    public void identityRealInfoBackFlow(String userId) {
        log.info("个人实名信息回流{}", userId);
        try {
            IdentityInfoRequest request = getSelfProxy().identityAuthQuery(userId);
            log.info("个人实名信息回流.userId={},request={}", userId, JSON.toJSONString(request));

            tianchengDataFlowService.identityAuth(request).whenComplete((res, throwable) -> {
                if (throwable != null) {
                    log.info("个人实名信息回流异常，userId={}",userId,throwable);
                } else {
                    log.info("个人实名信息回流响应，userId={}， response={}", userId,JSON.toJSONString(res));
                }
            });
        } catch (Exception e) {
            log.error("个人实名信息回流失败！异常信息：{}", e.getMessage(), e);
        }
    }

    /**
     * 个人信息-银行卡信息回流
     * @param bankInfoRequestDTO
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public BankInfoRequest bankInfoBackFlow(BankInfoRequestDTO bankInfoRequestDTO){
        //查询用户当前手机号
        UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(bankInfoRequestDTO.getUserId());
        if (userBasicInfo!=null){
            bankInfoRequestDTO.setMobilePhone(privacyMasks.decryptPrivacy(userBasicInfo.getMobileNo()));
        }

        BankInfoRequest request = new BankInfoRequest();
        BeanUtils.copyProperties(bankInfoRequestDTO, request);
        return request;
    }

    public void loginSuccess(LoginSuccessRequest request){
        doDataFlow(FunctionCodeEnum.LOGIN_SUCCESS, request, () -> tianchengDataFlowService.loginSuccess(request));
    }

    public void regiserSuccess(RegisterSuccessRequest request){
        doDataFlow(FunctionCodeEnum.REGISTER_SUCCESS, request, () -> tianchengDataFlowService.registerSuccess(request));
    }

    private void doDataFlow(FunctionCodeEnum functionCodeEnum, TianchengUapRequest request, Supplier<CompletableFuture<TianchengUapResponse>> f) {
        assert request != null && functionCodeEnum != null && f != null;
        log.info("{}###数据回流###request={}", functionCodeEnum.getDesc(), JSON.toJSONString(request));
    }

    private UserDataBackFlowService getSelfProxy() {
        return (UserDataBackFlowService) AopContext.currentProxy();
    }

    /**
     * 个人信息-身份认证信息回流
     * @param userId
     * @return
     */
    public IdentityInfoBackflowDTO getIdentityAuthBackflow(String userId){
        IdentityInfoBackflowDTO identityInfoBackflowDTO = new IdentityInfoBackflowDTO();
        identityInfoBackflowDTO.setUserId(userId.toString());

        //查询用户账户
        UcAccount ucAccount = userAccountMapperExt.selectByPrimaryKey(userId);
        if (ucAccount!=null){
            identityInfoBackflowDTO.setMobilePhone(decryptPrivacy(ucAccount.getMobileNo()));
        }

        //查询用户身份信息
        IdentityInfo identityInfo = identityInfoMapperExt.selectByPrimaryKey(userId);
        if (identityInfo!=null){
            identityInfoBackflowDTO.setRealName(identityInfo.getName());
            identityInfoBackflowDTO.setCardType(1);
            identityInfoBackflowDTO.setCardValidity(formatDate(identityInfo.getEndDate()));
            identityInfoBackflowDTO.setCardNO(decryptPrivacy(identityInfo.getIdCard()));
            identityInfoBackflowDTO.setCardAddress(identityInfo.getAddress());
            identityInfoBackflowDTO.setUpdateTime(identityInfo.getUpdateTime().getTime());
        }

        //查询用户实名认证状态
        DataStatus dataStatus = dataStatusMapperExt.selectByUserIdAndType(userId, UserDataTypeEnum.TWO_ELEMENT.getValue());
        if (dataStatus!=null && dataStatus.getDataStatus() != null && UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus()==dataStatus.getDataStatus().byteValue()){
            identityInfoBackflowDTO.setCertificationStatus(UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus().intValue());
        } else {
            identityInfoBackflowDTO.setCertificationStatus(UserDataStatusEnum.RealNameAuthStatus.NOT_CERTIFIED.getStatus().intValue());
        }
        if (dataStatus!=null){
            identityInfoBackflowDTO.setCertificationTime(dataStatus.getUpdateTime().getTime());
        }

        log.info("获取用户个人实名信息, userId:{}, identityInfoBackflowDTO:{}", userId, JSON.toJSONString(identityInfoBackflowDTO));

        return identityInfoBackflowDTO;
    }
}
